import { ElementRef } from '@angular/core';
import { interval, Subscription } from 'rxjs';

export abstract class HostWidthListener {
  intervalSub: Subscription;

  hostWidth: -1;

  constructor(
    private elementRef: ElementRef,
    private timeInterval = 1000,
  ) {
    this.startListen();
  }

  abstract onHostWidthChange(width: number);

  startListen() {
    this.hostWidth = this.elementRef.nativeElement.offsetWidth;

    this.intervalSub = interval(this.timeInterval).subscribe(() => {
      const width = this.elementRef.nativeElement.offsetWidth;
      if (this.hostWidth !== width) {
        this.hostWidth = width;
        this.onHostWidthChange(width);
      }
    });
  }

  stopListen() {
    this.intervalSub.unsubscribe();
  }
}
